package com.qqtech.qquan.draw.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBase;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.coupon.enums.CouponBaseBizzTypeDictEnum;
import com.qqtech.qquan.coupon.model.CouponBaseVo;
import com.qqtech.qquan.coupon.service.CouponBaseService;
import com.qqtech.qquan.draw.enums.DrawRageTypeEnum;
import com.qqtech.qquan.draw.model.DrawBase;
import com.qqtech.qquan.draw.model.DrawBaseQuery;
import com.qqtech.qquan.draw.model.DrawBaseVo;
import com.qqtech.qquan.draw.model.DrawBatch;
import com.qqtech.qquan.draw.model.DrawItemVo;
import com.qqtech.qquan.draw.service.DrawBaseService;
import com.qqtech.qquan.draw.service.DrawBatchService;
import com.qqtech.qquan.draw.service.DrawItemService;
import com.qqtech.qquan.draw.service.DrawSysDictService;
import com.qqtech.qquan.draw.service.DrawSysParamService;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.sys.controller.BaseAdminController;

@Controller
@RequestMapping(value = "/draw/base")
public class DrawBaseController extends BaseAdminController {
	@Resource
	private DrawBaseService drawBaseService;

	@Resource
	private CouponBaseService couponBaseService;

	@Resource
	private DrawItemService drawItemService;

	@Resource
	private DrawBatchService drawBatchService;

	@Resource
	private DrawSysParamService drawSysParamService;

	@Resource
	private DrawSysDictService drawSysDictService;

	@Resource
	private MallProductService mallProductService;

	@Resource
	private MallShopService mallShopService;

	@Resource
	private CommunityBaseService communityBaseService;

	@Override
	protected BaseService<DrawBase> getBaseService() {
		return drawBaseService;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/draw/drawBase-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(DrawBaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<DrawBaseVo> page = drawBaseService.queryPageList(query, pageKit);
		List<DrawBaseVo> drawList = page.getContent();
		if(drawList!=null && drawList.size()>0){
			CommunityBaseVo community = null;
			for(DrawBaseVo draw: drawList){
				if(draw.getRangeType()==DrawRageTypeEnum.COMMUNITY.getCode()){
					community = communityBaseService.getById(draw.getCommunityId());
					if(community!=null){
						draw.setCommunityName(community.getName());
					}
				}
			}
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/detail")
	public String detail(Integer id, Model model) {
		DrawBaseVo detailVo = drawBaseService.getById(id);
		if(detailVo!=null){
			if(detailVo.getRangeType()==DrawRageTypeEnum.COMMUNITY.getCode()){
				CommunityBaseVo community = communityBaseService.getById(detailVo.getCommunityId());
				if(community!=null){
					detailVo.setCommunityName(community.getName());
				}
			}
		}
		String category = "";
		model.addAttribute("category", category);
		model.addAttribute("detailVo", detailVo);
		return "/draw/drawBase-detail";
	}

	/**
	 * 创建成功
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Result add(DrawBaseVo addBaseVo, String drawItemIds, String rates, String quantitys) {
		Result ret = new Result();
		/*
		 *发布抽奖时，默认为未启动状态，不检查是否有抽奖正在进行
		if (addBaseVo.getRangeType() == DrawRageTypeEnum.COMMUNITY.getCode()) {// 社区抽奖，每个社区只能有一个抽奖进行中
			Integer communityId = addBaseVo.getCommunityId();// 社区ID
			CommunityBase community = communityBaseService.getById(communityId);
			if (community != null) {
				DrawBaseQuery drawBaseQuery = new DrawBaseQuery();
				drawBaseQuery.setNow(TimeUtil.now());
				drawBaseQuery.setStatus(YesNoEnum.YES.getCode());
				drawBaseQuery.setCommunityId(communityId);
				List<DrawBaseVo> drawBaseList = drawBaseService.queryList(drawBaseQuery);
				if (null != drawBaseList && drawBaseList.size() > 0) {
					ret.addErr(community.getName() + " 还有社区抽奖活动未结束");
					return ret;
				}
			} else {
				ret.addErr("该社区不存在");
				return ret;
			}

		} else {// 平台抽奖，只能有一个平台抽奖进行中
			DrawBaseQuery drawBaseQuery = new DrawBaseQuery();
			drawBaseQuery.setNow(TimeUtil.now());
			drawBaseQuery.setStatus(YesNoEnum.YES.getCode());
			drawBaseQuery.setRangeType(DrawRageTypeEnum.PLATFORM.getCode());// 平台抽奖
			List<DrawBaseVo> drawBaseList = drawBaseService.queryList(drawBaseQuery);
			if (null != drawBaseList && drawBaseList.size() > 0) {
				ret.addErr("还有平台抽奖活动未结束");
				return ret;
			}
		}
		 */
		if (addBaseVo.getRangeType() == DrawRageTypeEnum.COMMUNITY.getCode()) {
			Integer communityId = addBaseVo.getCommunityId();// 社区ID
			if (StringUtil.isNotBlank(drawItemIds)) {
				String[] drawItemList = drawItemIds.split(";");
				StringBuffer errorMsg = new StringBuffer();
				if (drawItemList.length > 0) {
					for (int i = 0; i < drawItemList.length; i++) {
						Integer drawItemId = Integer.valueOf(drawItemList[i]);
						DrawItemVo drawIitem = drawItemService.getById(drawItemId);
						if (drawIitem != null) {
							CouponBaseVo coupon = couponBaseService.getById(drawIitem.getCouponId());
							if (coupon != null
									&& coupon.getBizzType() == CouponBaseBizzTypeDictEnum.MALL_PRODUCT.getCode()) {
								MallProduct product = mallProductService.getById(coupon.getBizzId());// 商品
								if (product != null) {
									MallShop shop = mallShopService.getById(product.getShopId());// 店铺
									if (shop != null) {
										if (shop.getType() != null
												&& shop.getType().intValue() != MallShopTypeDictEnum.SUPERMARKET
														.getCode()
												&& (StringUtil.isBlank(shop.getExtCommunityIds())
														|| !shop.getExtCommunityIds().contains("" + communityId))) {
											errorMsg.append("实物奖品:" + drawIitem.getName() + ",不在抽奖社区！\n");
										}
									}
								}
							}
						}

					}
					if (errorMsg != null && errorMsg.length() > 0) {
						ret.addErr(errorMsg.toString());
						return ret;
					}
				}
			}
		} else {
			addBaseVo.setCommunityId(null);// 如果是平台抽奖，去掉社区ID属性
		}
		addBaseVo.setStatus(YesNoEnum.NO.getCode());//发布抽奖时默认 未启动
		int drawId = drawBaseService.insert(addBaseVo);
		List<DrawBatch> list = new ArrayList<DrawBatch>();
		if (StringUtil.isNotBlank(drawItemIds)) {
			String[] drawItemList = drawItemIds.split(";");
			String[] quantitysList = quantitys.split(";");
			String[] ratesList = rates.split(";");
			if (drawItemList.length > 0) {
				for (int i = 0; i < drawItemList.length; i++) {
					DrawBatch drawBatch = new DrawBatch();
					drawBatch.setDrawBaseId(drawId);
					drawBatch.setDrawItemId(Integer.valueOf(drawItemList[i]));
					drawBatch.setQuantity(Integer.valueOf(quantitysList[i]));
					drawBatch.setRate(Integer.valueOf(ratesList[i]));
					list.add(drawBatch);
				}
			}
		}
		drawBatchService.insertInBatch(list);
		return ret;
	}

	/**
	 * 去新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/toAdd")
	public String toAdd(Model model) {
		return "/draw/drawBase-add";
	}

	/**
	 * 去更新
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/toUpdate")
	public String toUpdate(Integer id, Model model) {
		DrawBaseVo drawBaseVo = drawBaseService.getById(id);
		if(drawBaseVo!=null){
			if(drawBaseVo.getRangeType()==DrawRageTypeEnum.COMMUNITY.getCode()){
				CommunityBaseVo community = communityBaseService.getById(drawBaseVo.getCommunityId());
				if(community!=null){
					drawBaseVo.setCommunityName(community.getName());
				}
			}
		}
		model.addAttribute("drawBaseVo", drawBaseVo);
		DrawBaseQuery drawBaseQuery = new DrawBaseQuery();
		List<DrawBaseVo> list = drawBaseService.queryList(drawBaseQuery);
		model.addAttribute("list", list);
		return "/draw/drawBase-update";
	}

	/**
	 * 创建成功
	 * 
	 * @param shareId
	 * @return
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(DrawBase drawBase) {
		Result ret = new Result();
		drawBaseService.updateById(drawBase);
		return ret;
	}

	/**
	 * 停止
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/down")
	@ResponseBody
	public Result down(Integer id) {
		Result ret = new Result();
		DrawBase drawBase = new DrawBase();
		drawBase.setId(id);
		drawBase.setStatus(YesNoEnum.NO.getCode());
		drawBaseService.updateById(drawBase);
		return ret;
	}

	/**
	 * 开启
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/up")
	@ResponseBody
	public Result up(Integer id) {
		Result ret = new Result();
		DrawBaseVo drawBaseDb = drawBaseService.getById(id);
		if(drawBaseDb==null){
			ret.addErr("该抽奖不存在");
			return ret;
		}
		if(drawBaseDb.getEndAt().getTime() < TimeUtil.now().getTime()){
			ret.addErr("该抽奖已过期");
			return ret;
		}
		if (drawBaseDb.getRangeType() == DrawRageTypeEnum.COMMUNITY.getCode()) {// 社区抽奖，每个社区只能有一个抽奖进行中
			Integer communityId = drawBaseDb.getCommunityId();// 社区ID
			CommunityBase community = communityBaseService.getById(communityId);
			if (community != null) {
				DrawBaseQuery drawBaseQuery = new DrawBaseQuery();
				drawBaseQuery.setNow(TimeUtil.now());
				drawBaseQuery.setStatus(YesNoEnum.YES.getCode());
				drawBaseQuery.setCommunityId(communityId);
				List<DrawBaseVo> drawBaseList = drawBaseService.queryList(drawBaseQuery);
				if (null != drawBaseList && drawBaseList.size() > 0) {
					ret.addErr(community.getName() + " 还有社区抽奖活动未结束,不能同时开启多个抽奖。");
					return ret;
				}
			} else {
				ret.addErr("该社区不存在");
				return ret;
			}
		} else {// 平台抽奖，只能有一个平台抽奖进行中
			DrawBaseQuery drawBaseQuery = new DrawBaseQuery();
			drawBaseQuery.setNow(TimeUtil.now());
			drawBaseQuery.setStatus(YesNoEnum.YES.getCode());
			drawBaseQuery.setRangeType(DrawRageTypeEnum.PLATFORM.getCode());// 平台抽奖
			List<DrawBaseVo> drawBaseList = drawBaseService.queryList(drawBaseQuery);
			if (null != drawBaseList && drawBaseList.size() > 0) {
				ret.addErr("还有平台抽奖活动未结束,不能同时开启多个平台抽奖。");
				return ret;
			}
		}
		
		DrawBase drawBase = new DrawBase();
		drawBase.setId(id);
		drawBase.setStatus(YesNoEnum.YES.getCode());
		drawBaseService.updateById(drawBase);
		return ret;
	}
}
